package com.kexun.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kexun.bo.PlayUrlBO;
import com.kexun.bo.SongBO;
import com.kexun.entity.PlayInfo;
import com.kexun.entity.SongInfo;
import com.kexun.platform.migu.Entrance;
import com.kexun.service.PlayInfoService;
import com.kexun.service.SongInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;

@Slf4j
@Component
public class DownloadTask implements ApplicationRunner {
    @Value("${localAddress}")
    private String localAddress;
    @Autowired
    private SongInfoService songInfoService;
    @Autowired
    private PlayInfoService playInfoService;


    public void saveSong(SongBO songBO, String group) {
        String songImg = songBO.getSongImg();
        String songName = songBO.getSongName();
        String singer = songBO.getSinger();
        String albumName = songBO.getAlbumName();
        String lrcText = songBO.getLrcText();
        List<PlayUrlBO> playUrls = songBO.getPlayUrls();
        boolean exist = songInfoService.findExist(songName, singer, albumName);
        if (!exist) {
            SongInfo songInfo = new SongInfo();
            songInfo.setSongName(songName);
            songInfo.setAlbumImageOut(songImg);
            songInfo.setSingerName(singer);
            songInfo.setAlbumName(albumName);
            songInfo.setLrcText(lrcText);
            songInfo.setCreateTime(new Date());
            songInfoService.save(songInfo);
            for (PlayUrlBO playUrl : playUrls) {
                PlayInfo playInfo = new PlayInfo();
                playInfo.setSongId(songInfo.getSongId());
                playInfo.setOutUrl(playUrl.getUrl());
                playInfo.setPlayType(playUrl.getType());
                playInfoService.save(playInfo);
                if (!StringUtils.isEmpty(playUrl.getUrl())) {
                    try {
                        String path = localAddress + "\\" + group + "\\" + songName + "\\";
                        File file = new File(path);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        String fileName = songName + getHzm(playUrl.getType());

                        String savePath = path + fileName;
                        savePath = savePath.replace(" ", "").replace("|", "");
                        File file1 = new File(savePath);
                        FileUtils.copyURLToFile(new URL(playUrl.getUrl()), file1);

                        System.out.println("歌曲: " + fileName + "保存到: " + file1.getPath());

                    } catch (Exception e) {
//                        log.error("文件保存失败:", e);
                    }
                }
            }
        }

    }

    private String getHzm(int type) {
        if (type == 1) {
            return ".mp3";
        }
        if (type == 2) {
            return ".mp3";
        }
        if (type == 3) {
            return ".flac";
        }
        return ".mp3";
    }


    public String saveTjGd() {
        Entrance entrance = new Entrance();
        JSONArray list = entrance.getTjGdList();
        for (int i = 0; i < list.size(); i++) {
            JSONObject gdItem = list.getJSONObject(i);
            String gdId = gdItem.getString("gdId");
            String gdName = gdItem.getString("gdName");
            List<SongBO> gdSong = entrance.getGdSong(gdId);
            for (SongBO songBO : gdSong) {
                try {
                    saveSong(songBO, gdName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "下载完成";
    }

    public void saveAllGd() {
        Entrance entrance = new Entrance();
        JSONArray list = entrance.getGdList("");
        System.out.println("歌单加载完成[" + list.size() + "],准备加载歌曲");
        for (int i = 0; i < list.size(); i++) {
            JSONObject gdItem = list.getJSONObject(i);
            String gdId = gdItem.getString("gdId");
            String gdName = gdItem.getString("gdName");
            List<SongBO> gdSong = entrance.getGdSong(gdId);
            System.out.println("歌曲加载完成:" + gdSong.size());
            for (SongBO songBO : gdSong) {
                try {
                    saveSong(songBO, gdName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static void main(String[] args) {
        Entrance entrance = new Entrance();
        JSONArray list = entrance.getTjGdList();
        System.out.println(list.toJSONString());
    }


    public void saveSingerSong() {
        Entrance entrance = new Entrance();
        List<Map<String, String>> singerList = entrance.getSingerList();
        for (Map<String, String> stringStringMap : singerList) {
            String href = stringStringMap.get("href");
            String singer = stringStringMap.get("singer");
            List<SongBO> singerSong = entrance.getSingerSong(href);
            System.out.println("开始入库");
            for (SongBO songBO : singerSong) {
                try {
                    saveSong(songBO, singer);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }






    @Override
    public void run(ApplicationArguments args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
//        executorService.execute(this::saveAllGd);
        FutureTask<String> stringFutureTask = new FutureTask<>(this::saveTjGd);
        executorService.execute(stringFutureTask);
//        executorService.execute(this::saveSingerSong);
        String s = stringFutureTask.get();
        System.out.println("=========" + s + "==========");
    }
}
